package com.ygqh.baby.plugin;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.*;
import java.sql.*;
import java.util.*;

/**
 * <p>
 * </p>
 * <p/>
 * Created by on 2015/11/12.
 */
public class Genterator {

	// 要生成哪些表 用逗号分隔
	public static String table_names = "yg_agent_level";

	public static final String packageName = "com.ygqh.baby";

	public static final String rootPath = "D:\\JavaProjects\\yiigoo/yg_service/src/main/";

	public static String template_path = rootPath + "resources/template";

	public static String servie_save_path = rootPath + "java/com/ygqh/baby/service/impl";

	public static String IService_save_path = rootPath + "java/com/ygqh/baby/service";

	public static String mapper_save_path = rootPath + "java/com/ygqh/baby/mapper/sqlmap_ext";

	public static String java_mapper_save_path = rootPath + "java/com/ygqh/baby/mapper";

	public static String DBDRIVER = "";
	public static String DBURL = "";
	public static String DBUSER = "";
	public static String DBPASS = "";

	static {
		Resource resource = new ClassPathResource("prop/jdbc.properties");
		Properties property = null;
		try {
			property = PropertiesLoaderUtils.loadProperties(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		DBDRIVER = property.getProperty("jdbc.driver");
		DBURL = property.getProperty("read.jdbc.url");
		DBUSER = property.getProperty("read.jdbc.username");
		DBPASS = property.getProperty("read.jdbc.password");
	}

	private static String getCloums4Sql(Table table) {

		List<Cloumn> cloumns = table.getCloumns();
		StringBuilder sb = new StringBuilder();
		for (Cloumn cloumn : cloumns) {
			sb.append(cloumn.getCloumn_Name()).append(",");
		}
		String result = sb.substring(0, sb.length() - 1);
		return result;
	}

	public static void main(String args[]) throws Exception {
		List<Table> tables = queryTables();
		for (Table table : tables) {
			String[] inputTables = table_names.split(",");
			for (String s : inputTables) {
				if (s.equals(table.getTableName())) {
					Map result = new HashMap();
					System.out.println(packageName);
					result.put("table", table);
					result.put("package", packageName);
					result.put("cloums", getCloums4Sql(table));
					System.out.println(getCloums4Sql(table));
					genteratorHtml("serviceImpl", table, result, "java");
					genteratorHtml("service", table, result, "java");
					genteratorHtml("mapper", table, result, "xml");
					genteratorHtml("javaMapper", table, result, "java");
				}
			}

		}
	}

	public static void genteratorHtml(String templateFile, Table table, Map result, String type) throws Exception {
		try {
			// 创建一个合适的Configration对象
			Configuration configuration = new Configuration();
			configuration.setDirectoryForTemplateLoading(new File(template_path));
			configuration.setObjectWrapper(new DefaultObjectWrapper());
			configuration.setDefaultEncoding("UTF-8"); // 这个一定要设置，不然在生成的页面中 会乱码
			// 获取或创建一个模版。
			Template template = configuration.getTemplate(templateFile + ".ftl");
			String fileName = "";
			if (templateFile.equals("serviceImpl")) {
				fileName = table.getClassName() + "ServiceImpl";
				fileName = servie_save_path + "//" + fileName + "." + type;
			} else if (templateFile.equals("service")) {
				fileName = table.getClassName() + "Service";
				fileName = IService_save_path + "//" + fileName + "." + type;
			} else if (templateFile.equals("javaMapper")) {
				fileName = table.getClassName() + "Mapper";
				fileName = java_mapper_save_path + "//" + fileName + "." + type;
			} else if (templateFile.equals("mapper")) {
				fileName = table.getClassName() + "Mapper";
				fileName = mapper_save_path + "\\" + fileName + "." + type;
			}
			Writer writer = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
			template.process(result, writer);
			System.out.println("恭喜，生成成功~~");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}

	public static List<Table> queryTables() {
		DatabaseMetaData dmd = null;
		Connection conn = null; // 表示数据库的连接对象
		// 列名
		List<Table> tables = new ArrayList<Table>();
		try {
			Class.forName(DBDRIVER); // 1、使用CLASS 类加载驱动程序
			conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); // 2、连接数据库
			DatabaseMetaData dbmd = conn.getMetaData();
			ResultSet resultSet = dbmd.getTables(null, "%", "%", new String[] { "TABLE" });
			while (resultSet.next()) {
				Table table = new Table();
				table.setCloumns(new ArrayList<Cloumn>());
				String tableName = resultSet.getString("TABLE_NAME");
				table.setTableName(tableName);
				table.setLowerClassName(lowerName(getCloumnName(tableName)));
				table.setClassName(captureName(getCloumnName(tableName)));

				ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");
				// System.out.println("表名：" + tableName + "\t\n表字段信息：");
				while (rs.next()) {
					Cloumn cloumn = new Cloumn();
					cloumn.setCloumn_Name(rs.getString("COLUMN_NAME"));
					cloumn.setCloumnName(getCloumnName(rs.getString("COLUMN_NAME")));
					cloumn.setRemark(rs.getString("REMARKS"));
					cloumn.setType(rs.getString("TYPE_NAME"));
					// System.out.println(cloumn.getCloumn_Name()+"---"+cloumn.getCloumnName());
					table.getCloumns().add(cloumn);
				}
				tables.add(table);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return tables;
	}

	public static String getCloumnName(String strFieldName) {
		int indx = strFieldName.indexOf("_");
		int count = 0;
		while (indx != -1) {
			count++;
			strFieldName = captureName(strFieldName, indx + 1);
			indx = strFieldName.indexOf("_", indx + count);
		}
		return strFieldName.replaceAll("_", "");
	}

	/**
	 * 某位置字母大写
	 *
	 * @param name
	 * @param indx
	 * @return
	 */
	public static String captureName(String name, int indx) {
		name = name.substring(0, indx) + name.substring(indx, indx + 1).toUpperCase() + name.substring(indx + 1);
		return name;
	}

	/**
	 * 首字母大写
	 *
	 * @param name
	 * @return
	 */
	public static String captureName(String name) {
		name = name.substring(0, 1).toUpperCase() + name.substring(1);
		return name;
	}

	public static String lowerName(String name) {
		name = name.substring(0, 1).toLowerCase() + name.substring(1);
		return name;
	}

	private String getRightUrl(String target) {
		return target.substring(6, target.length());
	}

}
